package com.atguigu.gmall.wms.config;

import com.rabbitmq.client.AMQP;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.apache.bcel.classfile.Code;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Configuration
public class RabbitMqCofig {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        // 生成者发送给交换机的确认回调
        rabbitTemplate.setConfirmCallback((correlationData,b,msg)->{
            if (!b){
                log.error(correlationData.getId()+msg);
            }
        });
        //交换机发送给队列的失败回调
        //Message var1, int var2, String var3, String var4, String var5
        rabbitTemplate.setReturnCallback((message, code,txt,exchange,routerKey)->{
            log.error("消息没有到达队列 状态码：{}，错误内容：{}，交换机：{}，路由键：{}",code,new String(message.getBody()),exchange,routerKey);
        });
    }

    //ORDER_EXCHANGE
    //创建延迟队列
    @Bean
    public Queue queue(){
        return QueueBuilder.durable("STOCK_TTL_QUEUE").
                withArgument("x-dead-letter-exchange", "ORDER_EXCHANGE").
                withArgument("x-dead-letter-router","stock-unlock").
                withArgument("x-message-ttl",100000).build();
    }

    //延迟队列绑定到交换机
    @Bean
    public Binding ttlBinding(){
        return new Binding("STOCK_TTL_QUEUE",
                Binding.DestinationType.QUEUE,
                "ORDER_EXCHANGE",
                "stock.ttl.order",null);
    }


}
